package org.wisdomdata.common;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.wisdomdata.framework.Extractor;

/**
 * 定义一个信息抽取者抽象类
 * 抽取者可以定义子抽取者，不过子抽取者是有顺序的
 * @author Clebeg 
 * @time 2014-12-06
 * */
public abstract class AbstractListExtractor implements Extractor{
	private static final Logger logger = 
			Logger.getLogger(AbstractListExtractor.class.getName());
	/**
	 * 抽取的信息的名字，如果名字为空或者NULL那么就以默认值作为名字，
	 * 或者用父抽取器的名字
	 * */
	private String extractName;
	public String getExtractName() {
		return extractName;
	}
	public void setExtractName(String extractName) {
		this.extractName = extractName;
	}
	
	private boolean isNeedAll = true;
	
	public boolean isNeedAll() {
		return isNeedAll;
	}
	public void setNeedAll(boolean isNeedAll) {
		this.isNeedAll = isNeedAll;
	}

	/**
	 * 定义需要处理的目标节点的内容
	 * */
	private Integer beginIndex;
	private Integer interval;
	private Integer endIndex;
	
	/**
	 * 解析需要的位置，比如没有填写，默认就是全部都要
	 * 
	 * */
	protected List<Integer> parsePosition() {
		
		if (getBeginIndex() == null || getInterval() == null ||
				getEndIndex() == null || getBeginIndex() > getEndIndex()) {
			logger.warning("you position arguments is  null or illegal, system will get all position!");
			setNeedAll(true);
			return null;
		}
		List<Integer> positions = new ArrayList<Integer>();
		for (int p = beginIndex; p <= endIndex; p += interval) {
			positions.add(p);
		}
		return positions;
	}
	
	
	public Integer getBeginIndex() {
		return beginIndex;
	}
	public void setBeginIndex(Integer beginIndex) {
		this.beginIndex = beginIndex;
	}
	public Integer getInterval() {
		return interval;
	}
	public void setInterval(Integer interval) {
		this.interval = interval;
	}
	public Integer getEndIndex() {
		return endIndex;
	}
	public void setEndIndex(Integer endIndex) {
		this.endIndex = endIndex;
	}
	
	public void extract() {
		//尝试三次
		int mark = 0;
		while(true) {
			mark++;
			try {
				if (prepareExtract()) {
					innerExtract();
					quitExtract();
				}
			} catch (Exception e) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				if (3 <= mark) {
					break;
				}
				else 
					continue;
			}	
			break;
		} 
				
	}
	public boolean prepareExtract() {
		return true;
	}

	public void quitExtract() {

	}
	
	
	
	
}
